package HBaseDemo;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HBaseAdmin;

import java.io.IOException;
import java.util.ResourceBundle;

public class HBaseUtils {
    //1.获取configuration对象
    private  static Configuration conf=null ;
    private  static Connection connection=null;
    private  static  HBaseAdmin admin=null;
    static {

        try {
            //1.获取configuration对象
            conf = HBaseConfiguration.create();
            //2.获取hbase配置文件的参数
            ResourceBundle hbase = ResourceBundle.getBundle("hbase");
            conf.set("hbase.zookeeper.quorum", hbase.getString("hbase.zookeeper.quorum"));
            conf.set("hbase.zookeeper.property.clientPort", hbase.getString("hbase.zookeeper.property.clientPort"));
            conf.set("zookeeper.znode.parent", hbase.getString("zookeeper.znode.parent"));
            //3.获取连接对象
            //连接HBase
            connection = ConnectionFactory.createConnection(conf);
            admin =(HBaseAdmin) connection.getAdmin();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static HBaseAdmin getAdmin() {

        return admin;
    }
    public static Configuration getConf(){
        return conf;
    }
    public static void main(String[] args) throws IOException {
        //创建初始化的命名空间
        initNameSpance("NameSpance", conf);
    }

    public static void initNameSpance(String namespance, Configuration conf) throws IOException {

        //命名空间描述器
        NamespaceDescriptor nd = NamespaceDescriptor
                .create(namespance)
                .addConfiguration("AUTHOR", "A")
                .build();
        //通过admin创建命名空间
        admin.createNamespace(nd);
        System.out.println("已初始化命名空间");
        //关闭资源
        close(admin);
    }
    //关闭资源
    public static void close(HBaseAdmin admin) {
        if(admin!=null){
            try {
                admin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (connection != null){
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
